package service

import (
	"gitee.com/duan_shengjie/user/domain/model"
	"gitee.com/duan_shengjie/user/domain/repository"
	"golang.org/x/crypto/bcrypt"
)

type IUserDataService interface {
	AddUser(user *model.User) (int64, error)
	DeleteUser(id int64) error
	UpdateUser(user *model.User, isChangePwd bool) error
	FindUserByName(userName string) (*model.User, error)
	CheckPwd(userName, pwd string) (bool, error)
}

type UserDataService struct {
	UserRepository repository.IUserRepository
}

func NewUserDataService(userRepository repository.IUserRepository) IUserDataService {
	return &UserDataService{UserRepository: userRepository}
}

// 添加用户
func (u *UserDataService) AddUser(user *model.User) (userId int64, err error) {
	pwdByte, err := GeneratePassword(user.HashPassword)
	if err != nil {
		return user.ID, err
	}
	user.HashPassword = pwdByte
	return u.UserRepository.CreateUser(user)
}

// 删除用户
func (u *UserDataService) DeleteUser(id int64) error {
	return u.UserRepository.DeleteByID(id)
}

// 更新用户
func (u *UserDataService) UpdateUser(user *model.User, isChangePwd bool) (err error) {
	if isChangePwd {
		pwdStr, err1 := GeneratePassword(user.HashPassword)
		if err1 != nil {
			return
		}
		user.HashPassword = pwdStr
	}
	err = u.UserRepository.UpdateUser(user)
	return
}

// 查找用户
func (u *UserDataService) FindUserByName(userName string) (user *model.User, err error) {
	return u.UserRepository.FindUserByName(userName)
}

// 验证密码
func (u *UserDataService) CheckPwd(userName, pwd string) (bool, error) {
	user, err := u.UserRepository.FindUserByName(userName)
	if err != nil {
		return false, err
	}
	return ValidatePassword(pwd, user.HashPassword)
}

// 加密用户密码
func GeneratePassword(pwd string) (string, error) {
	hashByte, err := bcrypt.GenerateFromPassword([]byte(pwd), bcrypt.DefaultCost)
	return string(hashByte), err
}

// 校验用户密码
func ValidatePassword(pwd string, hashed string) (isOk bool, err error) {
	err = bcrypt.CompareHashAndPassword([]byte(hashed), []byte(pwd))
	if err != nil {
		return
	}
	isOk = true
	return
}
